package notifier

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

type WechatWork struct {
	webhook string
	timeout time.Duration
	client  *http.Client
}

// NewWechatWork 创建企业微信通知实例
func NewWechatWork(webhook string, timeout time.Duration) *WechatWork {
	return &WechatWork{
		webhook: webhook,
		timeout: timeout,
		client: &http.Client{
			Timeout: timeout,
			Transport: &http.Transport{
				MaxIdleConns:    5,
				IdleConnTimeout: 30 * time.Second,
			},
		},
	}
}

// Send 实现Notifier接口
func (w *WechatWork) Send(ctx context.Context, content string) error {
	payload := struct {
		MsgType  string `json:"msgtype"`
		Markdown struct {
			Content string `json:"content"`
		} `json:"markdown"`
	}{
		MsgType: "markdown",
		Markdown: struct {
			Content string `json:"content"`
		}{
			Content: content,
		},
	}

	jsonData, err := json.Marshal(payload)
	if err != nil {
		return fmt.Errorf("marshal payload failed: %w", err)
	}

	req, err := http.NewRequestWithContext(ctx, "POST", w.webhook, bytes.NewBuffer(jsonData))
	if err != nil {
		return fmt.Errorf("create request failed: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := w.client.Do(req)
	if err != nil {
		return fmt.Errorf("send request failed: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
	}

	return nil
}

// Name 实现Notifier接口
func (w *WechatWork) Name() string {
	return "wechat_work"
}
